package test.lyj.tool;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.Images.Media;
import android.util.Log;


/**
 * 图像上传,本地保存方法
 * 
 * @title
 * @author ysy
 * @date 2010-11-17
 * @email 1234gogogo@sina.com.cn
 */
public class ImgFileService {

	public static final String Path_LocalCardImg = "/sdcard/DCIM/cardBox";

	public static final String Path_LocalHeadImg = "/sdcard/DCIM/cardBox/headImg";

	

	// public static void saveHeadImg2Server(Bitmap bm,String name){
	// ByteArrayOutputStream baos = new ByteArrayOutputStream();
	// bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
	// byte[] data = baos.toByteArray();
	//	
	// FormFile f = new FormFile(AppData.op_user.getImgCardId(),data);
	// Map<String, String> params = new HashMap<String, String>();
	// params.put("baId", AppData.op_user.getImgCardId());
	// params.put("bgimgindex", "1");
	// params.put("styleindex", "1");
	// params.put("styletype", "1");
	// ImgFileService.post2FWQ(params, new FormFile[] { f });
	// ImgFileService.saveHeadImg2Local(name, bm);
	// }

	

	/**
	 * 保存名片图片到本地
	 * 
	 * @param name
	 * @param bitmap
	 * @return
	 */
	public static void saveCardImg2Local(String name, Bitmap bitmap) {
		onwrite(name, Path_LocalCardImg, bitmap);
	}

	/**
	 * 保存头像到本地
	 * 
	 * @param name
	 * @param bitmap
	 * @return
	 */
	public static void saveHeadImg2Local(String name, Bitmap bitmap) {
		
		onwrite(name, Path_LocalHeadImg, bitmap);
	}

	public static Bitmap findCardImgByName(String id) {
		return findBitmapByPath(ImgFileService.Path_LocalCardImg + "/" + id
				+ ".png");
	}

	public static Bitmap findHeadImgByName(String id) {
		return findBitmapByPath(ImgFileService.Path_LocalHeadImg + "/" + id
				+ ".png");
	}

	public static void deleteAllImgBypath(String path) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			File pathFile = new File(path);
			if (Tool.DEBUG)
				Log.d("is", "delete..........");
			if (pathFile.exists()) {
				File[] fs = pathFile.listFiles();
				List<String> filenames = new ArrayList<String>();
				if (Tool.DEBUG)
					Log.d("is", "delete.........." + fs.length);
				for (int i = 0; i < fs.length; i++) {
					File f = fs[i];
					filenames.add(f.getName());
				}
				for (Iterator<String> iterator = filenames.iterator(); iterator
						.hasNext();) {
					String s = (String) iterator.next();
					File ff = new File(path + java.io.File.separator + s);
					if (Tool.DEBUG)
						Log.d("is", "delete.........." + ff);
					ff.delete();
				}
			}
			pathFile.deleteOnExit();
		}
	}

	private static void onwrite(String name, String path, Bitmap bitmap) {
		// path="/sdcard/DCIM/info";
		// name="/test2323.png";

		if (!name.endsWith("png")) {
			name += ".png";
		}

		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			File pathFile = new File(path);
			String abpath = path + "/" + name;
			File f = new File(abpath);
			if (!pathFile.exists()) {

				pathFile.mkdirs();
			}
			try {
				if (!f.exists()) {

					f.createNewFile();
				}

				FileOutputStream fout = new FileOutputStream(f);
				bitmap.compress(CompressFormat.PNG, 100, fout);
				fout.close();

			} catch (Exception e) {

			}
		}
	}
	/**
	 * 根据路径获取缩略图
	 * 如果高(maxHeigth)或者长(maxWidth)任何一个为0，则表示，无需做缩放
	 * @param path 图片路径
	 * @param maxWidth 长
	 * @param maxHeigth 高
	 * @param cutFlag 是否剪裁多余部分
	 * @return
	 */
	public static Bitmap findBitmapByPath2(String path,int maxWidth,int maxHeigth,boolean cutFlag) {
		//如果高或者长任何一个为0，则表示，无需做缩放
		if(maxWidth==0||maxHeigth==0){
			try {
				return BitmapFactory.decodeFile(path);
			} catch (Exception e) {
				return null;
			}
		}
		//下面做缩放操作	
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 1;
		options.inJustDecodeBounds = true;
//		// 获取这个图片的宽和高
		Bitmap dbbm = BitmapFactory.decodeFile(path, options); // 此时返回bm为空
		int dbHeight=options.outHeight;
		int dbWidth=options.outWidth;
		options.inJustDecodeBounds = false;
		if(Tool.DEBUG)
			Log.d("find db pic", "height width=="+dbHeight+"/"+dbWidth);
		//比较大小，确定以小那个比例缩放
		//大的那部分做剪裁
		int tempHeight=dbHeight/maxHeigth;
		int tempWidth=dbWidth/maxWidth;
		//如果比例太小，原图还没有要求图片大，则按原图大小直接返回
		if(tempHeight==tempWidth&&tempWidth==0){
			options.inSampleSize=1;
			options.outHeight=dbHeight;
		}else{
			if(tempHeight<tempWidth){
				options.inSampleSize=tempHeight;
				options.outHeight=maxHeigth;
			}else{
				options.inSampleSize=tempWidth;
				options.outWidth=maxWidth;
			}
		}
		try {
			FileInputStream stream = new FileInputStream(new File(path));
			Bitmap rbm=BitmapFactory.decodeStream(stream, null, options);
			if(!cutFlag){
				return rbm;
			}else{
				return cutBitmap(rbm, maxWidth,maxHeigth);
			}
			
		} catch (FileNotFoundException e) {
			return null;
		}
	}
	/**
	 * 根据路径找到原图，不做缩放
	 * @param path
	 * @return
	 */
	public static Bitmap findBitmapByPath(String path) {
		return findBitmapByPath2(path, 0, 0, false);
	}

	

	/**
	 * 截图 首先按比例缩放至预计高度和预计宽度。以比例小的优先缩放。 然后截取缩放以后多余的部分。
	 * 
	 * @param bm
	 *            原图
	 * @param width
	 *            预计高度 目前设置为60
	 * @param height
	 *            预计宽度
	 * @return
	 */
	public static Bitmap cutBitmap(Bitmap bm, int width, int height) {
		if (Tool.DEBUG)
			Log.d("cutBitmap", "resizemap=" + bm.getWidth() + "/"
					+ bm.getHeight() + "/" + width + "/" + height);
		// 原始宽度
		int w = bm.getWidth();
		// 原始高度
		int h = bm.getHeight();
		// 如果已经是最小了，则不做处理
		if (w < width && h < height)
			return bm;
		float resize = 1;
		int _x = 0, _y = 0;
		int maxlength = w;
		if (w > h) {
			_x = (w - h) / 2;
			maxlength = h;
			resize=((float) width) / h;
		}
		if (h > w) {
			_y = (h - w) / 2;
			resize=((float) height) / w;
		}
//		float hHresize = ((float) width) / h;
//		float hWresize = ((float) height) / w;
		Matrix m = new Matrix();// 矩阵
		m.postScale(resize, resize);// 设置矩阵比例
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, _x, _y, maxlength,
				maxlength, m, true);// 直接按照矩阵的比例把源文件画入进行

		return resizedBitmap;
	}

	public static Bitmap resizeBitmap(Bitmap bm, int width, int height) {
		if (Tool.DEBUG)
			Log.d("resizeBitmap", "resizemap=" + bm.getWidth() + "/"
					+ bm.getHeight() + "/" + width + "/" + height);
		int w = bm.getWidth();
		int h = bm.getHeight();
		float resize = 1;
		float s1 = ((float) width) / w;
		float s2 = ((float) height) / h;
		if (s1 > s2)
			resize = s2;
		else
			resize = s1;
		Matrix m = new Matrix();// 矩阵
		m.postScale(resize, resize);// 设置矩阵比例
		Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, w, h, m, true);// 直接按照矩阵的比例把源文件画入进行
		if (resizedBitmap.getWidth() > width
				|| resizedBitmap.getHeight() > height) {

			return resizeBitmap(resizedBitmap, 60, 60);
		}
		return resizedBitmap;
	}
}
